﻿using Koala.Pro.CodeGenerator.UI.Common;
using Koala.Pro.CodeGenerator.UI.Common.EntityProject;
using Koala.Pro.CodeGenerator.UI.DatabaseModel.Schema;
using System.Diagnostics;
using WeifenLuo.WinFormsUI.Docking;

namespace Koala.Pro.CodeGenerator.UI
{
    public partial class FrmUIGenerator : DockContent
    {
        private MainSetting setting = new MainSetting();

        public FrmUIGenerator()
        {
            InitializeComponent();

            Init();

            LoadProjectData();
        }

        private void LoadProjectData()
        {
            try
            {
                setting.Load();
                txtRootNameSpace.Text = setting.RootNameSpace;
                txtNoPrefix.Text = setting.NoPrefixOfTableName;
            }
            catch (Exception ex)
            {
                MessageUtil.ShowError("加载项目配置信息失败：" + ex.Message);
            }
        }

        private void Init()
        {
            try
            {
                string selectedDatabaseName = Program.global.MainView.ToolWin.GetSelectedDatabaseName();
                DatabaseInfo databaseInfo = Program.global.DbInstance.DatabaseList[selectedDatabaseName];

                if (databaseInfo.TableList == null || databaseInfo.TableList.Count <= 0)
                {
                    databaseInfo.ListTables();
                }

                cmbTableList.Items.Clear();
                foreach (var table in databaseInfo.TableList)
                {
                    cmbTableList.Items.Add(table.Key);
                }

                string selectedTableName = Program.global.MainView.ToolWin.GetSelectedTableName();
                if (selectedTableName.Length > 0)
                {
                    cmbTableList.Text = selectedTableName;
                }
            }
            catch
            {
                MessageUtil.ShowError("数据获取错误！");
            }
        }

        private void cmbTableList_SelectedIndexChanged(object sender, EventArgs e)
        {
            var tableName = cmbTableList.Text;
            if (tableName.Length > 0)
            {
                string selectedDatabaseName = Program.global.MainView.ToolWin.GetSelectedDatabaseName();
                DatabaseInfo databaseInfo = Program.global.DbInstance.DatabaseList[selectedDatabaseName];
                var tableInfo = databaseInfo.TableList[tableName];

                queryListBox.Items.Clear();
                listDisplayListBox.Items.Clear();
                editDataListBox.Items.Clear();
                dataCheckListBox.Items.Clear();

                foreach (string key in tableInfo.ColumnList.Keys)
                {
                    queryListBox.Items.Add(key);
                    listDisplayListBox.Items.Add(key);
                    editDataListBox.Items.Add(key);
                    if (tableInfo.ColumnList[key].IsPrimaryKey == false)
                    {
                        dataCheckListBox.Items.Add(key);
                    }
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (cmbTableList.Text.Length == 0) { return; }

            string selectedPath = string.Empty;
            var folderDialog = new FolderBrowserDialog();
            var result = folderDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                selectedPath = folderDialog.SelectedPath;

                MainSetting mainSetting = new MainSetting();
                mainSetting.Load();
                mainSetting.OutputDir = selectedPath;
                mainSetting.Save();
            }
            else
            {
                return;
            }

            string selectedDatabaseName = Program.global.MainView.ToolWin.GetSelectedDatabaseName();
            DatabaseInfo databaseInfo = Program.global.DbInstance.DatabaseList[selectedDatabaseName];

            var searchFields = new List<string>();
            foreach (var item in queryListBox.CheckedItems)
            {
                searchFields.Add(item.ToString() ?? "");
            }

            var searchDisplay = new List<string>();
            foreach (var item in listDisplayListBox.CheckedItems)
            {
                searchDisplay.Add(item.ToString() ?? "");
            }

            var editFields = new List<string>();
            foreach (var item in editDataListBox.CheckedItems)
            {
                editFields.Add(item.ToString() ?? "");
            }

            var editCheck = new List<string>();
            foreach (var item in dataCheckListBox.CheckedItems)
            {
                editCheck.Add(item.ToString() ?? "");
            }
            string selectedTableName = Program.global.MainView.ToolWin.GetSelectedTableName();
            var selectedTableNames = new List<string>() { selectedTableName };
            SqlSugarWpfProject.Execute(databaseInfo, selectedTableNames, searchFields, searchDisplay, editFields, editCheck, null, null);
        
            if (selectedPath != string.Empty)
            {
                OpenSelectedFolder(selectedPath);
            }
        }

        private void OpenSelectedFolder(string path)
        {
            try
            {
                Process.Start("explorer.exe", $"/select, \"{path}\"");
            }
            catch (System.ComponentModel.Win32Exception noExplorer)
            {
                //MessageBox.Show(noExplorer.Message);
            }
            catch (System.Exception genericEx)
            {
                //MessageBox.Show(genericEx.Message);
            }
        }
    }
}
